package net.thxjj.adminServer.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import cmcciot.onenet.nbapi.sdk.api.online.DeleteDeviceOpe;
import cmcciot.onenet.nbapi.sdk.entity.DeleteDevice;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.biz.aep_device_management.DeleteDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.DeleteDeviceResponse;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceResponse;
import net.thxjj.adminServer.dao.ProductDao;
import net.thxjj.adminServer.entity.*;
import net.thxjj.adminServer.websocket.NBServer;
import net.thxjj.sitermodel.Device;
import net.thxjj.sitermodel.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import net.thxjj.adminServer.dao.DeviceDao;
import net.thxjj.adminServer.service.IDeviceService;
import net.thxjj.adminServer.util.ParameterMap;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class DeviceService implements IDeviceService{

	private static final java.util.logging.Logger logger = Logger.getLogger(DeviceService.class.getCanonicalName());

	@Autowired
	private DeviceDao devicedao;

	@Autowired
	private ProductDao productDao;
	
	@Override
	public Device getDeviceInfo(String pm) {
		// TODO Auto-generated method stub
		return devicedao.getDeviceInfo(pm);
	}

	@Override
	public List<Device> getDeviceList(String imei,String prod_key,List<Long> deviceStatusFilter,List<Long> netStatusFilter) {

		return devicedao.getDeviceList(imei,prod_key,deviceStatusFilter,netStatusFilter);
	}

	@Async("asyncExecutor")
	@Override
	public void updateDeviceOnline(ParameterMap pm) {
		devicedao.updateDeviceOnLine(pm);
	}

	@Async("asyncExecutor")
	@Override
	public void updateDeviceOffline(ParameterMap pm) {
		devicedao.updateDeviceOffLine(pm);
	}


	@Override
	public Integer getSmokeStatus(String device_id) {
		return null;
	}


	@Override
	public List<Device> getAllDeviceList() {

		return devicedao.getAllDeviceList();
	}

	@Override
	public HashMap<String, Object> modifyHeartTime(long min, String deviceId) {
		try {
			devicedao.updateDeviceHeartTime(min,deviceId);
			return ResponseModel.getModel(ResultEnum.SUCCESS,null);
		}catch (Exception e){
			return ResponseModel.getModel(ResultEnum.FAILED,null);
		}

	}

	@Override
	public List<Device> getDeviceListByProductId(String productId) {
		return devicedao.getDeviceListByProductId(productId);
	}

	@Override
	public HashMap<String, Object> setDevicesUpdate(List<Device> listout,List<Device> listin) {
		try {
			for (Device device:listout){
				devicedao.setDeviceOut(device.getDeviceId());
			}
			if(listin.size()>0){
				devicedao.saveDevice(listin);
			}
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return ResponseModel.getModel(ResultEnum.FAILED,null);
		}
		return ResponseModel.getModel(ResultEnum.SUCCESS,null);
	}

	@Override
	public HashMap<String, Object> deleteDevice(Device device) {

		if("aep".equals(device.getPlatform())){
			try {
			AepDeviceManagementClient client = AepDeviceManagementClient.newClient()
					.appKey(Const.APPKEY).appSecret(Const.APPSECRET)
					.build();

			Product product = productDao.getProduct(device.getProdKey());
			DeleteDeviceRequest request = new DeleteDeviceRequest();
			// set your request params here
			 request.setParamMasterKey(product.getApiKey());	// single value
			 request.setParamProductId(device.getProdKey());	// single value
			 request.setParamDeviceIds(device.getDeviceId());	// single value
			// request.addParamDeviceIds(deviceIds);	// or multi values

			 DeleteDeviceResponse deleteDeviceResponse = client.DeleteDevice(request);
			 client.shutdown();
				String body = new String(deleteDeviceResponse.getBody());
				JSONObject jsonObject = JSON.parseObject(body);
				int code = jsonObject.getIntValue("code");
				String msg = jsonObject.getString("msg");
				if(code==0){
					devicedao.setDeviceOut(device.getDeviceId());
					return ResponseModel.getModel(ResultEnum.SUCCESS,null);
				}else {
					return ResponseModel.getModel(msg,code,null);
				}
// more requests
			} catch (Exception e) {
				e.printStackTrace();
				return ResponseModel.getModel(ResultEnum.FAILED,null);
			}

		}else if("onenet".equals((device.getPlatform()))){
			Product product = productDao.getProduct(device.getProdKey());
			DeleteDevice deleteDevice = new DeleteDevice(device.getDeviceId());
			DeleteDeviceOpe deleteDeviceOpe = new DeleteDeviceOpe(product.getApiKey());
			JSONObject jsonResult = deleteDeviceOpe.operation(deleteDevice,null);
			int code = jsonResult.getIntValue("errno");
			String msg = jsonResult.getString("error");
			if(code==0){
				devicedao.setDeviceOut(device.getDeviceId());
				return ResponseModel.getModel(ResultEnum.SUCCESS,null);
			}else{
				return ResponseModel.getModel(msg,code,null);
			}

		}else{
			return ResponseModel.getModel(ResultEnum.THIS_DEVICE_NOT_OPERATOR_DEVICE,null);
		}
	}


}
